package com.freshman_registration.controller;

import cn.hutool.core.convert.Convert;
import com.freshman_registration.mapper.DormitoryMapper;
import com.freshman_registration.pojo.Dormitorys;
import com.freshman_registration.service.DormitoryService;
import com.freshman_registration.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/dormitory")
@Slf4j
public class DormitoryController {

    @Autowired
    private DormitoryService dormitoryService;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    /** 列表 */
    /**
     * 分页查询所有宿舍床位信息
     * @param pageNum 页码（默认1）
     * @param pageSize 每页条数（默认5）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {

        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询数据（复用原查询方法）
        List<Dormitorys> rows = dormitoryService.listAll();

        // 包装分页信息
        PageInfo<Dormitorys> pageInfo = new PageInfo<>(rows);
        Map<String, Object> ret = new HashMap<>(2);
        ret.put("total", pageInfo.getTotal()); // 总条数
        ret.put("rows", rows); // 当前页数据
        return Result.success(ret);
    }

    /** 新增入住：系统按 1-4 自动分配床位，同一房间≤4人 */
    @PostMapping("/allocate")
    public Result<Integer> allocate(@RequestBody Dormitorys dormitory) {
        try {
            int added = dormitoryService.allocateBed(dormitory); // 1. 拿返回值
            return Result.success(added);                      // 2. 把数量返给前端
        } catch (Exception e) {
            log.error("allocate error", e);
            return Result.fail(e.getMessage());
        }
    }

//    分配宿舍并入住
@PostMapping("/check-in")
public Result<Void> checkIn(@RequestParam String studentId) {
    try {
        log.info("学生{}开始办理入住", studentId);
        dormitoryService.checkIn(studentId);
        log.info("学生{}入住成功", studentId);
        return Result.success();
    } catch (Exception e) {
        log.error("学生{}入住失败", studentId, e);
        return Result.fail(e.getMessage());
    }
}
    @GetMapping("/bed/list")
    public Result<Map<String, Object>> bedList(
            @RequestParam(required = false) String buildingNo,
            @RequestParam(required = false) String roomNo,
            @RequestParam(required = false) String bedStatus,
            @RequestParam(required = false) String genderLimit,
            @RequestParam(defaultValue = "1")  Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 打印入参，调试一目了然
        log.info("【条件查询】buildingNo={}, roomNo={}, bedStatus={}, genderLimit={}, currentPage={}, pageSize={}",
                buildingNo, roomNo, bedStatus, genderLimit, currentPage, pageSize);

        PageHelper.startPage(currentPage, pageSize);
        List<Dormitorys> rows = dormitoryMapper.selectByCondition(buildingNo, roomNo, bedStatus, genderLimit);

        PageInfo<Dormitorys> pageInfo = new PageInfo<>(rows);
        Map<String, Object> ret = new HashMap<>(2);
        ret.put("total", pageInfo.getTotal());
        ret.put("rows", rows);
        return Result.success(ret);
    }
    // 1. 批量退宿（软）
    @PostMapping("/batch-checkout")
    public Result<Void> batchCheckOut(@RequestBody List<Long> dormIds) {
        dormitoryService.batchCheckOut(dormIds);
        return Result.success();
    }

    // 2. 批量删除（硬）
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDelete(@RequestBody List<Long> dormIds) {
        dormitoryService.batchDelete(dormIds);
        return Result.success();
    }
//    分页查询/////////////////////////////
@PostMapping("/bed/page")
public Result<Map<String, Object>> bedPage(@RequestBody Map<String, Object> param) {
    int pageNum = Convert.toInt(param.get("pageNum"), 1);
    int pageSize = Convert.toInt(param.get("pageSize"), 10);
    String building = Convert.toStr(param.get("building"));
    String room = Convert.toStr(param.get("room"));
    String status = Convert.toStr(param.get("status"));
    String gender = Convert.toStr(param.get("gender"));

    // 直接调自己的 Mapper
    PageHelper.startPage(pageNum, pageSize);
    List<Dormitorys> rows = dormitoryMapper.selectByCondition(building, room, status, gender);

    PageInfo<Dormitorys> pageInfo = new PageInfo<>(rows);
    Map<String, Object> ret = new HashMap<>(2);
    ret.put("total", pageInfo.getTotal());
    ret.put("rows", rows);
    return Result.success(ret);
}

//确认入住
    /**
     * 确认入住并记录当前时间
     *
     * @param dormId 床位ID
     * @return 操作结果
     */
    @PostMapping("/confirm-checkin")
    public Result<String> confirmCheckIn(@RequestParam(required = false) Integer dormId) {
        if (dormId == null) {
            return Result.fail("床位ID不能为空");
        }
        try {
            dormitoryService.confirmCheckIn(dormId);
            return Result.success("入住确认成功");
        } catch (RuntimeException e) {
            log.error("确认入住失败，dormId:{}", dormId, e);
            return Result.fail(e.getMessage());
        }
    }
    // 在 DormitoryController 里追加
    @GetMapping("/of-student")
    public Result<Dormitorys> getByStudentId(@RequestParam String studentId) {
        // 1. 先拿到学生的 dorm_id
        Integer dormId = dormitoryMapper.getDormIdByStudentId(studentId);
        if (dormId == null) {
            return Result.fail("该学生尚未分配宿舍");
        }
        // 2. 再用 dorm_id 当主键去宿舍表查一条
        Dormitorys room = dormitoryMapper.selectByPrimaryKey(dormId);
        return Result.success(room);
    }
    // 新增：通过学号和姓名查询宿舍信息
    @GetMapping("/by-student-info")
    public Result<Dormitorys> getDormByStudentInfo(
            @RequestParam String studentId,
            @RequestParam String name) {
        try {
            Dormitorys dorm = dormitoryService.getDormByStudentIdAndName(studentId, name);
            return Result.success(dorm);
        } catch (Exception e) {
            log.error("查询宿舍信息失败", e);
            return Result.fail(e.getMessage());
        }
    }
}